package com.atguigu.study.base.rwlock;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author 快点干早点散
 * @Create 2025/4/25 21:21
 * Description:
 */

public class LockDowngradingDemo2 {
    ReadWriteLock relock = new ReentrantReadWriteLock();
    int data = 0;

    public int readData() {
        relock.readLock().lock();
        try {
            return data;
        } finally {
            relock.readLock().unlock();
        }
    }

    public void updata(int newData) {
        relock.writeLock().lock();
        System.out.println(Thread.currentThread().getName()+"获取写锁");
        try {
            data = newData;
            System.out.println(Thread.currentThread().getName()+"新值 = " + newData);
            relock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"获取读锁");
        } finally {
            relock.writeLock().unlock();
            System.out.println(Thread.currentThread().getName()+"释放写锁");
        }
        try {
            int currentData = readData();
            System.out.println(currentData);
        } finally {
            relock.readLock().unlock();
            System.out.println(Thread.currentThread().getName()+"释放读锁");
        }

    }

    public static void main(String[] args) {
        LockDowngradingDemo2 lockDowngradingDemo2 = new LockDowngradingDemo2();
        new Thread(() -> {
            lockDowngradingDemo2.updata(50);
        }, "a").start();
        new Thread(() -> {
            lockDowngradingDemo2.readData();
        }, "b").start();


    }

}
